######################################################################
# Time-stamp: <05/08/09 16:11:49 ostolop>
#
# Package: EP::Common::DBI
#
# Base class for DB classes. Sets up inheritable cnxn.
######################################################################
package EP::Common::DBI;

use strict;

use EP::Config;
# use Class::DBI for use with Postgress, or Class::DBI::Oracle for use with Oracle
use base 'Class::DBI';

my $dsn      = $EP::Config::h->{DB};
my $user     = $EP::Config::h->{DBUSER};
my $password = $EP::Config::h->{DBPASSWORD};
my $attr     = $EP::Config::h->{DBATTR};

# create inheritable DB connection (named main)
EP::Common::DBI->connection( $dsn, $user, $password, $attr ) or die $DBI::errstr;
EP::Common::DBI->autoupdate(1);

sub do_transaction
    {
    my ( $class, $code, @args ) = @_;

    $class->_invalid_object_method('do_transaction()') if ref($class);

    my @return_values = ();
    my $dbh = $class->db_Main;

    # Localize AutoCommit database handle attribute
    # and turn off for this block.
    local $dbh->{AutoCommit};  # Note: Leaks memory with Perl 5.6.1.

    eval{
        @return_values = $code->(@args);
        $class->dbi_commit;
        };

    if ($@)
        {
        my $error = $@;

        eval{
            $class->dbi_rollback;
            };

        if ($@)
            {
            my $rollback_error = $@;
            $class->_croak("Transaction aborted: $error; (rollback failed: $rollback_error).\n");
            }
        else
            {
            $class->_croak("Transaction aborted (rollback successful): $error.\n");
            }
        }
    return(@return_values);
    }

1;
